<template>
  <div class="tabs-container">
    <el-tabs
      v-model="activeName"
      type="card"
      closable
      @tab-click="onTabClick"
      @tab-remove="onTabRemove"
    >
      <el-tab-pane
        v-for="tab in visitedTabs"
        :key="tab.fullPath"
        :name="tab.fullPath"
      >
        <template #label>
          <span class="tab-label">
            <el-icon v-if="getIconComponent(tab.icon)"><component :is="getIconComponent(tab.icon)" /></el-icon>
            {{ tab.title }}
          </span>
        </template>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { House, User, Document } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

const ICON_MAP = { House, User, Document }
const getIconComponent = (name) => (name && ICON_MAP[name]) || null

const visitedTabs = ref([])
const activeName = ref('')

const persist = () => {
  try {
    sessionStorage.setItem('visitedTabs', JSON.stringify(visitedTabs.value))
  } catch {}
}

const restore = () => {
  try {
    const raw = sessionStorage.getItem('visitedTabs')
    if (raw) {
      const parsed = JSON.parse(raw)
      if (Array.isArray(parsed)) visitedTabs.value = parsed
    }
  } catch {}
}

const ensureHome = () => {
  const hasHome = visitedTabs.value.some(t => t.fullPath === '/home')
  if (!hasHome) {
    visitedTabs.value.unshift({
      title: '首页',
      fullPath: '/home',
      path: '/home',
      icon: 'House'
    })
  }
}

const addCurrentRouteAsTab = () => {
  const { fullPath, path, meta } = route
  const title = meta?.title || '未命名'
  const icon = meta?.icon || null
  if (!visitedTabs.value.some(t => t.fullPath === fullPath)) {
    visitedTabs.value.push({ title, fullPath, path, icon })
    persist()
  }
  activeName.value = fullPath
}

const onTabClick = (pane) => {
  const target = visitedTabs.value.find(t => t.fullPath === pane.paneName)
  if (target && route.fullPath !== target.fullPath) {
    router.push(target.fullPath)
  }
}

const onTabRemove = (name) => {
  const idx = visitedTabs.value.findIndex(t => t.fullPath === name)
  if (idx === -1) return
  const removed = visitedTabs.value.splice(idx, 1)[0]
  persist()
  if (activeName.value === removed.fullPath) {
    const next = visitedTabs.value[idx] || visitedTabs.value[idx - 1] || visitedTabs.value[0]
    if (next) router.push(next.fullPath)
  }
}

onMounted(() => {
  restore()
  ensureHome()
  addCurrentRouteAsTab()
})

watch(() => route.fullPath, () => {
  ensureHome()
  addCurrentRouteAsTab()
})
</script>

<style lang="scss" scoped>

.tab-label {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>
